// miniprogram/pages/startPage/startPage.js
var app = getApp();
const host = app.globalData.host;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    getUserInfoButtonFunction: "bindGetUserInfo",
    showGetUserInfo: true,
    userInfo: null,
    hasUserInfo: false,
    showPanel: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '登录中',
    })

    var that = this;
    // 向服务器发送登录信息
    wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        console.log('[云函数] [login]: ', res)
        app.globalData.openid = res.result.openid;
        if (res.result.isRegistered) {
          app.globalData.isRegistered = true,
            // 获取用户信息
            wx.getSetting({
              success: res => {
                wx.hideLoading();
                if (res.authSetting['scope.userInfo']) {
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                  console.log("获得用户信息");
                  wx.getUserInfo({
                    success: res => {
                      console.log(res);
                      this.setData({
                        userInfo: res.userInfo
                      })
                      app.globalData.userInfo = res.userInfo;
                      //我是真的想偷懒
                      //这里用云服务器登陆完之后 再把用户的数据上传到服务器上
                      wx.request({
                        url: host + 'city360/updateUser',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded',
                        },
                        method: "POST",
                        data: {
                          nickName: app.globalData.userInfo.nickName,
                          avatarUrl: app.globalData.userInfo.avatarUrl,
                          openid: app.globalData.openid
                        },
                        complete: res => {
                          console.log("更新数据完毕", res);
                          wx.request({
                            url: host + 'city360/queryUser',
                            method: "POST",
                            header: {
                              'content-type': 'application/x-www-form-urlencoded',
                            },
                            data: {
                              openid: app.globalData.openid
                            },
                            complete: res=>{
                              app.globalData.userIdentity = res.data.userIdentity;
                            }
                          })
                        }
                      });
                      wx.redirectTo({
                        url: '../index/index',
                      });
                    }
                  });
                } else {
                  wx.hideLoading();
                  that.setData({
                    showGetUserInfo: true,
                    showPanel: true,
                  })
                }
              }
            })
        } else {
          app.globalData.isRegistered = false;
          wx.hideLoading();
          that.setData({
            showGetUserInfo: true,
            showPanel: true,
          })
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },


  bindGetUserInfo: function(e) {
    // 查看是否授权
    var that = this;
    wx.getUserInfo({
      complete: (res) => {
        console.log("在注册页面", res);
        if (res.errMsg === "getUserInfo:fail auth deny") {
          that.setData({
            userInfo: null,
            hasUserInfo: false,
          })
          wx.showModal({
            title: '提示',
            content: '请您打开授权，否则无法正常使用该小程序',
            showCancel: false
          });
          return;
        }
        app.globalData.userInfo = res.userInfo;
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          showGetUserInfo: false,
        });
        if (app.globalData.isRegistered) {
          wx.request({
            url: host + 'city360/updateUser',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: "POST",
            data: {
              nickName: app.globalData.userInfo.nickName,
              avatarUrl: app.globalData.userInfo.avatarUrl,
              openid: app.globalData.openid
            },
            complete:res=>{
              console.log("更新数据完毕",res);
            }
          });
          wx.redirectTo({
            url: '../index/index',
          })
        } else {
          that.setData({
            showChoose: true
          })
        }

      }
    })
  },
  choose: function(e) {
    console.log(e);
    var dict = {
      'A': '居民',
      'B': '社区管理人员',
      'C': '企业用户',
      'D': '其他'
    }
    var id = e.target.id;
    const db = wx.cloud.database();
    const _ = db.command;
    wx.showLoading({
      title: '加载中',
      mask: true,
    });
    db.collection("users").add({
      data: {
        openid: app.globalData.openid,
        identity: dict[id],
        userInfo: this.data.userInfo,
      }
    }).then(res => {
      wx.hideLoading();
      //向服务器发送信息 注册
      wx.request({
        url: host + 'city360/insertUser',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        method: "POST",
        data: {
          nickName: app.globalData.userInfo.nickName,
          avatarUrl: app.globalData.userInfo.avatarUrl,
          openid: app.globalData.openid,
          userIdentity: dict[id]
        },
        complete: res=>{
          console.log("上传数据完毕", res);
        }
      });
      wx.redirectTo({
        url: '../index/index',
      })
    })
  },
})